package com.open.party.cloud.view.home.dangWuMiShu

import android.annotation.SuppressLint
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import androidx.core.content.ContextCompat
import com.jiangyy.easydialog.CommonDialog
import cn.android.x.model.data.ResultInfo
import cn.android.x.parent.AppEventBusTitleBaseActivity
import com.open.party.cloud.R
import com.open.party.cloud.model.DiaoChaWenJuanBean
import com.open.party.cloud.model.DiaoChaWenJuanQuestionBean
import com.open.party.cloud.model.DiaoChaWenJuanResultBean
import com.open.party.cloud.model.DiaoChaWenJuanSubmitBean
import com.open.party.cloud.viewModel.BizViewModel
import com.sinothk.android.utils.XUtils
import com.sinothk.switchTabView.style1.UIUtil
import kotlinx.android.synthetic.main.dwms_diao_cha_wen_juan_detail.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*
import kotlin.collections.indices

class DwmsDiaoChaWenJuanDetailActivity : AppEventBusTitleBaseActivity(), View.OnClickListener {

    private var viewModel: BizViewModel? = null
    private var questionnaireId = ""

    var questionList: ArrayList<DiaoChaWenJuanQuestionBean>? = null

    override fun getLayoutResId(): Int = R.layout.dwms_diao_cha_wen_juan_detail

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setViewTitle("问卷")

        questionnaireId = intent.getStringExtra("id") as String
        viewModel = BizViewModel()
        viewModel!!.getDiaoChaWenJuanDetail(questionnaireId)

        submitBtn.setOnClickListener(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun eventBusCallback(result: ResultInfo<DiaoChaWenJuanBean>) {
        if (result.eventType != "getDiaoChaWenJuanDetail") {
            return
        }
        hideLoadingDialog()
        // 获取题目
        when (result.code) {
            ResultInfo.SUCCESS -> {
                if (result.data != null) {
                    showData(result.data)
                } else {
                    XUtils.toast().show("数据异常")
                }
            }
            ResultInfo.TOKEN_OVERDUE -> {
                XUtils.toast().show("Token过期，请重新登录")
            }
            else -> {
                XUtils.toast().show(result.msg)
            }
        }
    }

//    private val resultMap = HashMap<String, Boolean>()

    @SuppressLint("SetTextI18n")
    private fun showData(data: DiaoChaWenJuanBean) {
        titleTv.text = XUtils.string().getNotNullValue(data.title)
        contentTv.text = XUtils.string().getNotNullValue(data.content)

        questionList = data.list

        if (questionList != null && questionList!!.size > 0) {

            for (index in questionList!!.indices) {

                var qTitleTv: TextView? = null

                val questionBean = questionList!![index]
                val questionNum = index + 1

                when (questionBean.type) {
                    0 -> {
                        val view01 = LayoutInflater.from(this).inflate(R.layout.kao_shi_item_01, null)
                        qTitleTv = view01.findViewById(R.id.qTitleTv)

                        val radioGroup: RadioGroup = view01.findViewById(R.id.radioGroup)
                        for (subIndex in questionBean.list.indices) {
                            val operationItem = questionBean.list[subIndex]

                            val rb = RadioButton(this)
                            rb.text = operationItem.option
                            rb.setTextColor(ContextCompat.getColor(this@DwmsDiaoChaWenJuanDetailActivity, R.color.page_content))
                            rb.paint.textSize = UIUtil.sp2px(this, 13f).toFloat()

                            // 点击事件
                            rb.setOnCheckedChangeListener { _, isChecked ->
                                questionList!![index].list[subIndex].isSelected = isChecked
                                if (isChecked) {
                                    questionList!![index].list[subIndex].answer = operationItem.option
                                } else {
                                    questionList!![index].list[subIndex].answer = ""
                                }
                            }

                            radioGroup.addView(rb, subIndex)
                        }

                        itemsView.addView(view01, index)
                    }
                    1 -> {
                        val view02 = LayoutInflater.from(this).inflate(R.layout.kao_shi_item_02, null)
                        qTitleTv = view02.findViewById(R.id.qTitleTv)

                        val checkBoxView: LinearLayout = view02.findViewById(R.id.checkBoxView)

                        for (subIndex in questionBean.list.indices) {
                            val operationItem = questionBean.list[subIndex]

                            val cb = CheckBox(this)
                            cb.text = operationItem.option
                            cb.setTextColor(ContextCompat.getColor(this@DwmsDiaoChaWenJuanDetailActivity, R.color.page_content))
                            cb.paint.textSize = UIUtil.sp2px(this, 13f).toFloat()
                            cb.setOnCheckedChangeListener { _, isChecked ->
                                questionList!![index].list[subIndex].isSelected = isChecked

                                if (isChecked) {
                                    questionList!![index].list[subIndex].answer = operationItem.option
                                } else {
                                    questionList!![index].list[subIndex].answer = ""
                                }
                            }
                            checkBoxView.addView(cb, subIndex)
                        }

                        itemsView.addView(view02, index)
                    }
                    2 -> {
                        val view03 = LayoutInflater.from(this).inflate(R.layout.kao_shi_item_03, null)
                        qTitleTv = view03.findViewById(R.id.qTitleTv)
                        val contentEt: EditText = view03.findViewById(R.id.contentEt)
                        contentEt.addTextChangedListener(object : TextWatcher {
                            override fun afterTextChanged(s: Editable?) {
                            }

                            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                            }

                            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                                questionList!![index].answer = s.toString()
                            }
                        })

                        itemsView.addView(view03, index)
                    }
                    else -> {
                    }
                }

                if (qTitleTv != null) {
                    // 题号
                    qTitleTv.text = "$questionNum、${XUtils.string().getNotNullValue(questionBean.subject)}"
                }
            }
        }
    }

    override fun onClick(v: View?) {
        when (v) {
            submitBtn -> {
                submit()
            }
        }
    }

    private fun submit() {
        val resultArr = getResult()

        when {
            resultArr.isEmpty() -> {
                XUtils.toast().show("没有回答问题，不能提交")
            }
            else -> {
                CommonDialog.Builder(this)
                    .setTitle("重要提醒")
                    .setCanceledOnTouchOutside(false)
                    .setMessage("是否确定提交答题信息？")
                    .setPositiveButton("提交") {

                        val submitBean = DiaoChaWenJuanSubmitBean()
                        submitBean.questionnaireId = questionnaireId
                        submitBean.resultList = resultArr

                        showLoadingDialog("正在提交")
                        viewModel!!.submitDiaoChaWenJuanResultSet(submitBean)

                    }.setNegativeButton("取消") {
                    }.show()
            }
        }
    }

    // 获得结果集
    private fun getResult(): Array<DiaoChaWenJuanResultBean> {
        // 已做选项答案集合
        val resultList = ArrayList<DiaoChaWenJuanResultBean>()

        for (questionBean in questionList!!) {

            if (questionBean.type == 2) {
                // 问答题没有子选项
                val resultBean = DiaoChaWenJuanResultBean()
                resultBean.questionnaireId = questionBean.questionnaireId
                resultBean.itemId = questionBean.id
                resultBean.answer = XUtils.string().getNotNullValue(questionBean.answer)

                resultList.add(resultBean)

            } else if (questionBean.type == 0 || questionBean.type == 1) {

                // 选择题
                for (itemBean in questionBean.list) {

                    if (itemBean.isSelected) {
                        val resultBean = DiaoChaWenJuanResultBean()
                        resultBean.questionnaireId = itemBean.questionnaireId
                        resultBean.itemId = itemBean.itemId
                        resultBean.optId = itemBean.id
                        resultBean.answer = XUtils.string().getNotNullValue(itemBean.answer)

                        resultList.add(resultBean)
                    }
                }
            }
        }

        return resultList.toTypedArray()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun eventBus2Callback(result: ResultInfo<Boolean>) {
        if (result.eventType != "submitDiaoChaWenJuanResultSet") {
            return
        }
        hideLoadingDialog()

        when (result.code) {
            ResultInfo.SUCCESS -> {
                if (result.data != null && result.data) {
                    XUtils.toast().show("投票成功")
                    finish()
                } else {
                    XUtils.toast().show("数据异常")
                }
            }
            ResultInfo.TOKEN_OVERDUE -> {
                XUtils.toast().show("Token过期，请重新登录")
            }
            else -> {
                XUtils.toast().show(result.msg)
            }
        }
    }
}